package com.alfayun.fiscalriskanalysis.report;

import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CellService {

    @Autowired
    private CellRepository cellRepository;
    
    @Autowired
    private ReportRepository reportRepository;
    
    @Autowired
    private ReportGroupRepository reportGroupRepository;
    
    @Transactional
    public Report add(Integer reportId, List<Cell> cells)throws NoSuchReportException {
        
        Report report = reportRepository.findById(reportId).orElseThrow(NoSuchReportException::new);
        if(cells != null && cells.size()>0) {
            for(int i=0;i<cells.size();i++) {
                Cell cell = cells.get(i);
                report.completeStatus = CompleteStatus.completed;
                reportRepository.save(report);
                if(cell.getId()!=null) {
                    Optional<Cell> data = cellRepository.findById(cell.getId());
                    if(data.isPresent()) {
                        Cell c = data.get();
                        c.value = cell.value;
                        cellRepository.save(c);
                    }
                }
                cell.report = report;
                cellRepository.save(cell);
                
                //更改报表組状态
                ReportGroup reportGroup = report.reportGroup;
                List<Report> list = reportRepository.findByReportGroupId(reportGroup.getId());
                if(list!=null && list.size()>0) {
                    boolean isComplete = true;
                    reportGroup.completeStatus = CompleteStatus.completed;
                    for(Report rpReport : list) {
                        if(rpReport.completeStatus.equals(CompleteStatus.uncompleted)) {
                            isComplete = false;
                        }
                    }
                    if(!isComplete) {
                        reportGroup.completeStatus = CompleteStatus.uncompleted;
                    }
                    reportGroupRepository.save(reportGroup);
                }
            }
        }
        return report;
    }
}
